import { useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useSelector, useStore } from 'react-redux';

import { findCities } from '@/api/MaiZuo';

import { changeCity, changeCityList } from '../redux/features/citySlice';
import { clearCinemaList } from '../redux/features/cinemaSlice';

export const useCityList = () => {
  const list = useSelector((state) => state.CityReducer.list);

  const { dispatch } = useStore();

  useEffect(() => {
    list.length === 0 &&
      findCities().then((res) => {
        dispatch(changeCityList(res.cities));
      });
    return () => {};
  }, [list.length, dispatch]);
  return {
    list,
  };
};

export const useHandeleClick = () => {
  const navigate = useNavigate();
  const { dispatch } = useStore();

  const handleClick = useCallback(
    (city) => {
      let { cityId: id, name } = city;
      // 切换城市
      dispatch(changeCity({ id, name }));
      // 清空影院缓存
      dispatch(clearCinemaList());
      navigate('/cinema');
    },
    [dispatch, navigate]
  );
  return { handleClick };
};
